home *** CD-ROM | disk | FTP | other *** search
- Path: lrz-muenchen.de!news
- From: watzka@stat.uni-muenchen.de (Kurt Watzka)
- Newsgroups: comp.lang.c
- Subject: Re: Why are &apple and apple, where apple is an array, the same
- Date: 19 Apr 1996 08:27:13 GMT
- Organization: Leibniz-Rechenzentrum, Muenchen (Germany)
- Distribution: world
- Message-ID: <4l7ip1$ft4@sparcserver.lrz-muenchen.de>
- References: <AD9C7BE9966828AF7@ad49-131.compuserve.com>
- NNTP-Posting-Host: sun2.lrz-muenchen.de
-
- 101641.317@compuserve.com (Martin Mamo) writes:
-
- >The following C program contains two printf's. They both
- >give the same answer, despite the fact one gives the
- >value of apple and the other &apple.
-
- And the behaviour of the program is undefined anyway, so why
- are you surprised by that.
-
- >I know in C, an array variable is the address of the
- >first element.
-
- In C an array variable is, well, an array variable. Used in
- an expression (with some minor exceptions) an array name
- decays to the address of the first element.
-
- >So why do C compilers on both Macs and PCs
- >allow you to take an address of an address?
-
- You take the address of an array, which is perfectly legal in C.
-
- >Why does
- >apple and &apple, where apple is an array variable, give
- >the same result.
-
- Because both give you a pointer to the beginning of "apple".
-
- >Please can you reply by e-mail to me as well, as I check
- >newsgroups less often than my e-mail. Thanks.
-
- So you will obviously have to wait until you check this
- newsgroup again until you read this answer. If you want to
- save bandwidth, as for e-mail replies and offer to post
- a summary.
-
- >#include <stdio.h>
-
- >void main(void)
-
- I will not comment on this.
-
- >{
-
- > char apple[10];
- > apple[0] = 0;
- >
- > printf( "%lu\n", apple );
-
- "apple" is a "char *" in this context, and you can print it
- with printf using "printf("%p\n", (void *) apple)". Whether
- the cast to "void *" is needed in this situation may be open
- to debate because the internal representation of a "char *"
- cannot be different from the internal representation of a
- "void *" in C.
-
- > printf(" %lu\n", &apple );
-
- "apple" is a "char (*)[10]" in this context, and you can
- print it with printf using "printf("%p\n", (void *)&apple)".
- The internal representation of a pointer to an array of 10
- char can be different from the internal representation of a
- "void *", so the cast _is_ necessary in this context.
-
- >}
-
- See the FAQ for comp.lang.c for a _good_ explanation of
- "arrays" and "pointers".
-
- Kurt
- --
- | Kurt Watzka Phone : +49-89-2180-6254
- | watzka@stat.uni-muenchen.de
-